package light.head.controller.el;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Url;
import light.head.dao.el.CourseDAO;
import light.head.dao.el.TopicAnswerDAO;
import light.head.dao.el.TopicCourseRelationDAO;
import light.head.dao.el.TopicDAO;
import light.head.dao.sys.OrganDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.model.el.Course;
import light.head.model.el.Topic;
import light.head.model.el.TopicAnswer;
import light.head.model.el.TopicCourseRelation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping(value = Url.C_TOPIC)
public class TopicController extends SupporterController{
	private TopicDAO topicDAO;
	private CourseDAO cDAO;
	private TopicAnswerDAO taDAO;
	private TopicCourseRelationDAO tcrDAO;
	private OrganDAO organDAO;
	
	@RequestMapping(Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response){
		return new ModelAndView(Url.TOPIC_INIT);
	}
	
	@RequestMapping(Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response){
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.CONTENT, Parm.DELETED,Parm.CC,Parm.TDC,Parm.TYPE);
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		if(topicDAO.findByMap(oc,map, pb) == RESULT.SUCCESS){
			request.setAttribute(Parm.PAGE_BEAN, pb);
		}
		return new ModelAndView(Url.TOPIC_LIST);
	}
	
	@RequestMapping(Url.EDIT)
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response){
		String code = request.getParameter(Parm.CODE);
		if(isNotNull(code)){
			Topic topic = topicDAO.get(Integer.parseInt(code));
			if(topic != null){
				//题目
				topic.setItemList(taDAO.findKeyByCode(Integer.parseInt(code)));
				request.setAttribute(Parm.INFO, topic);
			}
			List<Course> cList = cDAO.findCourseByCode(Integer.parseInt(code));
			request.setAttribute(Parm.LIST, cList);
		}
		return new ModelAndView(Url.TOPIC_EDIT);
	}
	
	@RequestMapping(Url.SAVE)
	@Transactional(rollbackFor = Exception.class)
	public void save(Topic t, HttpServletRequest request, HttpServletResponse response){
		String codes = request.getParameter(Parm.CODES);
		if(t == null || codes == null){
			print(response,Msg.ERROR);
		}
		RESULT result =  RESULT.ERROR;
		Integer cu = cu_code(request);
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		Date time = new Date();
		//添加
		if(t.getCode() == null){
			t.setCt(time);
			t.setDeleted(false);
			t.setCu(cu);
			t.setOc(oc);
			result = topicDAO.add(t);
			if(result == RESULT.SUCCESS){
				List<Integer> codeList = new ArrayList<Integer>();
				String[] cs = codes.split(",");
				for(int i = 0; i < cs.length; i++){
					codeList.add(Integer.parseInt(cs[i]));
				}
				//保存题目和课程的关系
				TopicCourseRelation temp = null;
				for(int i = 0; i < codeList.size(); i++){
					temp = new TopicCourseRelation();
					temp.setCc(codeList.get(i));
					temp.setTc(t.getCode());
					result = tcrDAO.add(temp);
					if(result == RESULT.ERROR){
						break;
					}
				}
				//题目答案添加
				if(t.getItemList() != null){
					for(TopicAnswer key : t.getItemList()){
						if(isNotNull(key.getAnswer())){
							key.setCt(time);
							key.setDeleted(false);
							key.setCu(cu);
							key.setOc(oc);
							key.setTc(t.getCode());
							if(t.getType() == 3){
								key.setIsRight(true);
							} else {
								if(key.getIsRight() != null){
									key.setIsRight(true);
								} else {
									key.setIsRight(false);
								}
							}
							result = taDAO.add(key);
							if(result == RESULT.ERROR){
								break;
							}
						}
					}
				}
			}
		} else { // 修改
			result = topicDAO.update(t);
			if(result == RESULT.SUCCESS){
				//修改课程
				List<Course> oldList = cDAO.findCourseByCode(t.getCode());//获取老课程的code
				List<Integer> newList = new ArrayList<Integer>();//修改后新课程的code
				String[] cs = codes.split(",");
				for(int i = 0; i < cs.length; i++){
					newList.add(Integer.parseInt(cs[i]));
				}
				//删除不要的课程
				List<Integer> delList = new ArrayList<Integer>();
				int i = 0;
				int len = newList.size();
				Integer code = null;
				for (Course old : oldList) {
					i = 0;
					for (; i < len; i ++) {
						code = newList.get(i);
						if (null != code && code.equals(old.getCode()))
							break;
					}
					if (i == len){
						delList.add(old.getCode());
					}
				}
				for (Integer co : delList){
					TopicCourseRelation temp = tcrDAO.findTCRByCCAndTc(t.getCode(), co);
					tcrDAO.del(temp);
				}
				
				boolean s = false;
				List<Integer> list = new ArrayList<Integer>();
				for (int j = 0; j < newList.size(); j++) {
					for (int k = 0; k < oldList.size(); k++) {
						if (newList.get(j) == oldList.get(k).getCode()) {
							s = false;
							break;
						} else
							s = true;
					}
					if (s) {
						list.add(newList.get(j));
					}
				}
				//添加新的课程
				for(Integer c : list){
					TopicCourseRelation temp = new TopicCourseRelation();
					temp.setCc(c);
					temp.setTc(t.getCode());
					result = tcrDAO.add(temp);
					if(result == RESULT.ERROR){
						break;
					}
				}
			}
			//修改或删除答案
			/** 删除编辑时删除的明细 */
			List<TopicAnswer> oldList = taDAO.findKeyByCode(t.getCode());
			if (null != oldList && oldList.size() > 0) {
				List<Integer> delCodes = new ArrayList<Integer>();
				int i = 0;
				int len = t.getItemList().size();
				Integer code = null;
				for (TopicAnswer old : oldList) {
					i = 0;
					for (; i < len; i ++) {
						code = t.getItemList().get(i).getCode();
						if (null != code && code.equals(old.getCode()))
							break;
					}
					if (i == len)
						delCodes.add(old.getCode());
				}
				for (Integer co : delCodes){
					TopicAnswer tk = taDAO.get(co);
					if(tk != null){
						tk.setDeleted(true);
						result = taDAO.upd(tk);
						if(result == RESULT.ERROR){
							break;
						}
					}
				}
			}
			//添加或修改答案信息
			for (TopicAnswer tk : t.getItemList()) {
				if (tk.getCode() == null) {
					if (isNotNull(tk.getAnswer())) {
						tk.setCt(time);
						tk.setDeleted(false);
						tk.setCu(cu);
						tk.setOc(oc);
						tk.setTc(t.getCode());
						if(t.getType() == 3){
							tk.setIsRight(true);
						} else {
							if(tk.getIsRight() != null){
								tk.setIsRight(true);
							} else {
								tk.setIsRight(false);
							}
						}
						if (taDAO.add(tk) != RESULT.SUCCESS){
							break;
						}
					}
				} else {
					if (taDAO.update(tk) != RESULT.SUCCESS){
						break;
					}
				}
			}
		} 
		if(result == RESULT.SUCCESS){
			print(response,Msg.SUCCESS);
		} else {
			print(response,Msg.ERROR);
		}
		
	}
	
	@RequestMapping(Url.AID_INIT)
	public ModelAndView aidInit(HttpServletRequest request, HttpServletResponse response){
		String codes = request.getParameter(Parm.CODES);
		if(codes != null){
			request.setAttribute(Parm.CODES, codes);
		}
		return new ModelAndView(Url.TOPIC_COURSE_INIT);
	}
	
	@RequestMapping(Url.AID_LIST)
	public ModelAndView aidList(HttpServletRequest request, HttpServletResponse response){
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.NAME, Parm.DELETED, Parm.CODES);
		cDAO.aidFindByMap(cu_organCode(request), map, pb);
		request.setAttribute(Parm.PAGE_BEAN, pb);
		String codes = map.get(Parm.CODES);
		if(isNotNull(codes)){
			List<Course> clist = cDAO.findCourseByCodes(codes);
			request.setAttribute(Parm.LIST,clist);
		}
		return new ModelAndView(Url.TOPIC_COURSE_LIST);
	}
	@Autowired
	public void setTopicDAO(TopicDAO topicDAO) {
		this.topicDAO = topicDAO;
	}
	@Autowired
	public void setTaDAO(TopicAnswerDAO taDAO) {
		this.taDAO = taDAO;
	}
	@Autowired
	public void setTcrDAO(TopicCourseRelationDAO tcrDAO) {
		this.tcrDAO = tcrDAO;
	}
	@Autowired
	public void setcDAO(CourseDAO cDAO) {
		this.cDAO = cDAO;
	}
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}

	
	
	
}
